<template>
  <el-dialog
    draggable
    overflow
    v-model="visible"
    :title="titleMap[mode]"
    :width="900"
    destroy-on-close
    @closed="$emit('closed')"
  >
    <sk-tabs type="border-card">
      <el-tab-pane ref="tab" label="基础信息">
        <el-form
          :model="form"
          :rules="rules"
          ref="dialogForm"
          label-width="70px"
          class="newform"
        >
          <el-row>
            <el-col :span="24">
              <el-descriptions title="原订单信息" :column="4" border label-align="right">
                <el-descriptions-item>
                  <template #label>往来</template>
                  {{ form.company.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>单号</template>
                  {{ form.relation_code }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>流转号</template>
                  {{ form.batchno }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>入库日期</template>
                  {{ form.in_date }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>单据日期</template>
                  {{ form.old_billdate }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>产品</template>
                  {{ form.material.spec }}
                  {{ form.material.name }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>颜色</template>
                  {{ form.color_name }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>缸号</template>
                  {{ form.dyelot ?? "无" }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>实际</template>
                  {{ form.fect_auxiliary_quantity ?? 0 }}包 {{ form.fect_quantity }}KG
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>码单</template>
                  {{ form.auxiliary_quantity ?? 0 }}包 {{ form.quantity }}KG
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>单价</template>
                  {{ form.price }}
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>金额</template>
                  {{ form.amount }}
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>备注</template>
                  {{ form.oldremark.data }}
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :span="24">
              <el-descriptions title="售后信息" :column="4" border label-align="right">
                <el-descriptions-item>
                  <template #label>单号</template>
                  <el-input
                    v-model="form.code"
                    :disabled="true"
                    :placeholder="'自动生成'"
                  ></el-input>
                </el-descriptions-item>
                <el-descriptions-item>
                  <template #label>单据日期</template>
                  <el-date-picker
                    v-model="form.billdate"
                    type="date"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择日期"
                    style="width: 120px"
                  >
                  </el-date-picker>
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>类别</template>
                  <skDicSelect
                    v-model="form.complaint_id"
                    :code="'PurchaseComplaint'"
                    style="width: 60px"
                  >
                  </skDicSelect>
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label>折扣金额</template>
                  <el-input
                    v-model="form.discount"
                    :disabled="discountdisabled"
                    clearable
                    :placeholder="discountplaceholder"
                  ></el-input>
                </el-descriptions-item>

                <el-descriptions-item>
                  <template #label><span style="color: red">*</span>备注</template>
                  <el-input v-model="form.remark" clearable></el-input>
                </el-descriptions-item>
              </el-descriptions>

              <sc-VxeTable
                ref="save"
                :gridEvts="gridEvts"
                :data="form.details"
                :gridOps="gridOps"
                :tablecode="'purchase_complaint_save'"
              >
              </sc-VxeTable>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="附件">
        <sk-upload
          v-model="form.attachments"
          :limit="10"
          draggable
          tip="单个文件不要超过10M,请上传图像格式文件"
        >
        </sk-upload>
      </el-tab-pane>
    </sk-tabs>

    <template #footer>
      <el-button @click="visible = false">取 消</el-button>
      <el-button type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>

  <skBrowserChoose
    v-model="openChooseDlg"
    :name="'storage_all_browser'"
    @close="openChooseDlg = false"
    @select="additems"
    :params="getStorageParams()"
  >
  </skBrowserChoose>
</template>

<script>
import skBrowserChoose from "@/components/skBrowserChoose";

import skDicSelect from "@/components/skDicSelect";
import skAutoChoose from "@/components/skAutoChoose";
import XEUtils from "xe-utils";
export default {
  emits: ["success", "closed"],
  components: { skAutoChoose, skDicSelect, skBrowserChoose },
  data() {
    return {
      mode: "add",
      openChooseDlg: false,
      gridEvts: {
        choose: () => (this.openChooseDlg = true),
      },
      titleMap: {
        add: "新增",
        edit: "编辑",
      },
      handleSuccessFn: null,
      form: {
        id: "",
        company: { name: "" },
        oldremark: {},
        billdate: this.$TOOL.SYS_DATE(),
        material: {},
        price: 0,
        quantity: 0,
        discount: null,
        details: [],
        complaint_id: 2,
        moisture: {},
        remark: "",
        attachments: [],
      },
      rules: {
        complaint_id: { required: true, message: "请选择售后类别" },
      },
      visible: false,
      isSaveing: false,
      gridOps: {
        height: 205,
        editRules: {
          price: [{ required: true, message: "单价必填" }],
        },
        columns: [
          {
            field: "fect_auxiliary_quantity",
            event: {
              keyup: ({ row }) => {
                row["auxiliary_quantity"] = row["fect_auxiliary_quantity"];
                row["amount"] = row["quantity"] * row["price"] ?? 0;
              },
            },
          },
          {
            field: "fect_quantity",
            event: {
              keyup: ({ row }) => {
                row["quantity"] = row["fect_quantity"];
                row["amount"] = row["quantity"] * row["price"] ?? 0;
              },
            },
          },
          {
            field: "quantity",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"] ?? 0;
              },
            },
          },
          {
            field: "price",
            event: {
              keyup: ({ row }) => {
                row["amount"] = row["quantity"] * row["price"] ?? 0;
              },
            },
          },
          {
            field: "amount",
            event: {
              keyup: ({ row }) => {
                row["price"] = row["amount"] / row["quantity"];
              },
            },
          },
        ],
      },
    };
  },
  computed: {
    discountdisabled() {
      return this.form.complaint_id != 4;
    },
    discountplaceholder() {
      if (this.discountdisabled) {
        return "折价才可以填";
      }
      return "请输入折价金额！";
    },
  },

  watch: {
    "form.price"(val) {
      this.form.amount = this.form.quantity * val;
    },
    "form.quantity"(val) {
      this.form.amount = this.form.price * val;
    },
  },
  mounted() {
    let userInfo = this.$TOOL.data.get("USER_INFO");
    this.form.department_id = userInfo.department_id;
  },
  methods: {
    getStorageParams() {
      let params = [{ iscustomer: 0 }];
      if ((this.form.material.id ?? 0) > 0) {
        params.push({ "material.id": this.form.material.id });
      }
      return params;
    },

    additems(items) {
      this.openChooseDlg = false;
      if (items.length != 1 && this.form.company.name == "") {
        return this.$message.error("初建，必须先选择一条，确定供应商!！");
      }

      items.map(row => {
        delete row.id;
        row["fect_auxiliary_quantity"] = row["auxiliary_quantity"] = XEUtils.toNumber(
          row["available_auxiliary_quantity"]
        );
        row["fect_quantity"] = row["quantity"] = XEUtils.toNumber(
          row["available_quantity"]
        );
        row["price"] = this.form.price;
        row["amount"] = XEUtils.toNumber(row["quantity"] * this.form.price);
        this.form.details.push(row);
      });
    },

    //显示
    open(mode = "add") {
      this.mode = mode;
      this.visible = true;
      return this;
    },
    setHandle(v) {
      this.handleSuccessFn = v;
    },
    //表单提交方法
    submit() {
      if ((this.form.remark ?? "") == "") {
        return this.$message.error("备注必须填写！");
      }
      this.$refs.dialogForm.validate(async valid => {
        if (valid) {
          this.isSaveing = true;
          if (this.form.complaint_id != 5) {
            const errMap = await this.$refs.save.xGrid.validate(true);
            if (errMap) {
              this.$message.error("价格必须填写！");
              this.isSaveing = false;
              return;
            }
          }
          var res = await this.$API.purchase.complaint.save.post(this.form);
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit("success", this.form, this.mode);
            this.visible = false;
            this.$message.success("操作成功");
            if (this.handleSuccessFn != null) {
              this.handleSuccessFn();
            }
          }
        }
      });
    },
    getItems(code) {
      return this.$API.purchase.complaint.details
        .post({
          filter: [{ code: code }],
        })
        .then(v => {
          return v.data.rows.map(vv => {
            vv["amount"] = -vv["amount"];
            vv["quantity"] = -vv["quantity"];
            vv["auxiliary_quantity"] = -vv["auxiliary_quantity"];
            vv["fect_quantity"] = -vv["fect_quantity"];
            vv["fect_auxiliary_quantity"] = -vv["fect_auxiliary_quantity"];
            return vv;
          });
        });
    },
    getInfo(red_id) {
      return this.$API.purchase.storage.list
        .post({
          filter: [{ id: red_id }],
        })
        .then(v => {
          return v.data.rows[0];
        });
    },
    //表单注入数据
    async setData(data) {
      this.getInfo(data.red_id).then(v => {
        Object.assign(this.form, this.$TOOL.removeNull(v), this.$TOOL.removeNull(data));
      });
      this.getItems(data.code).then(res => {
        this.form.details = res;
      });
      return this;
    },
  },
};
</script>
<style scope>
.newform .el-descriptions__label {
  width: 90px;
}
.newform .el-descriptions__content {
  width: 12.5%;
}
</style>
